import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  PermissionsAndroid,
  DeviceEventEmitter,
  Platform,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  ImageButton,
  LinearBoardButton,
  LinearButton,
  TextButton,
} from '../../components/Button';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {LinerBoardTextInput} from '../../components/TextInput';
import {NormalHeader} from '../../components/NavigationHeader';
import {
  follow,
  query,
  updateUser,
  getClubInfo,
  registClub,
} from '../../api/user';
import {showToast} from '../../components/Toast';
import {updateUserInfo} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {BASE_API} from '../../config';
import LinearGradient from 'react-native-linear-gradient';
import {ScrollView} from 'react-native-gesture-handler';
import ModalHandler from '../../components/ModalHandler';

class ApplyClubScreen extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      joinClub: false,
      modalVisible: false,
      loading: false,
      success: false,
      password: '',
      gasUsed: 0,
      fee: -1,
    };
  }

  componentDidMount() {
    this._queryUserInfo();
    getClubInfo().then((resp) => {
      console.log('getClubInfo', resp);
      this.setState({
        fee: resp.data.fee,
      });
    });
  }

  _queryUserInfo = () => {
    query({
      userToken: this.props.userInfo.token,
    }).then((resp) => {
      let user = resp.data;
      this.setState({
        joinClub: user.joinClub,
      });
    });
  };

  opennow = () => {
    console.log(this.state.fee);
    if (this.state.fee < 0) {
      return;
    }
    if (this.state.fee == 0) {
      this.sendJoinClubRequest();
    } else {
      WalletUtils.getRegisterClubGasPrice()
        .then((res) => {
          this.setState({
            gasUsed: res,
            modalVisible: true,
          });
        })
        .catch((err) => {
          console.log('获取失败');
        });
    }
  };

  _handlerView = () => {
    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            marginTop: 0,
            lineHeight: 40,
            color: '#6902F4',
            fontSize: 18,
          }}>
          Confirm your transaction
        </Text>
        <Image
          style={{height: 1, width: '100%', marginBottom: 20}}
          source={require('../../assets/auction/line.png')}></Image>
        <View style={{width: '100%'}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>
              Call Function
            </Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>
              apply for club membership
            </Text>
          </View>
        </View>
        <View style={{width: '100%', marginBottom: 10}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 40, color: '#6902F4'}}>Gas Fee</Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 40,
              }}>{`${this.state.gasUsed}${this.props.gasSymbol}`}</Text>
          </View>
        </View>
        <LinerBoardTextInput
          placeholder="Your wallet password"
          secureTextEntry
          defaultValue={this.state.password}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
        />
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'flex-end',
            width: '100%',
            // marginTop: 10,
            marginBottom: 20,
          }}>
          <LinearBoardButton
            buttonStyle={{width: 100, height: 35, marginRight: 20}}
            text="Cancel"
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
          />
          <LinearButton
            buttonStyle={{width: 100, height: 35, marginRight: 20}}
            text="Confirm"
            onPress={this.handlerConfirm}
          />
        </View>
      </View>
    );
  };

  sendJoinClubRequest = (hash) => {
    let params = {
      userToken: this.props.userInfo.token,
    };
    if (hash) {
      params.hash = hash;
    }
    this._showLoading('Loading', () => {
      registClub(params)
        .then(async (resp) => {
          console.log(resp);
          this.setState({
            joinClub: true,
          });
          await this.props.updateUserInfo({
            ...this.props.userInfo,
            joinClub: true,
          });
          DeviceEventEmitter.emit('UserInfoChanged', {});
          showToast('Application succeeded!');
          this._hideLoading(() => {
            this.props.navigation.navigate('MyClub');
          });
        })
        .catch((err) => {
          console.log(err);
          this._hideLoading();
          this._showAlert({content: err.msg});
        });
    });
  };

  handlerConfirm = () => {
    if (!this.state.password) {
      return;
    }
    Keyboard.dismiss();
    this.setState(
      {
        loading: true,
      },
      async () => {
        try {
          var privateKey = await WalletUtils.privateKeyOfKeystore(
            this.props.userInfo.keystore,
            this.state.password,
          );
        } catch (err) {
          console.log('错误' + err);
          this.setState(
            {
              password: '',
              modalVisible: false,
              loading: false,
            },
            () => {
              this._showAlert({content: 'invalid password'});
            },
          );
          return;
        }

        let coin = null;
        for (var i = 0; i < this.props.coins.length; i++) {
          if (this.props.coins[i].symbol.toLowerCase() == 'signin') {
            coin = this.props.coins[i];
            break;
          }
        }
        WalletUtils.transferErc20(
          privateKey,
          this.props.manager.address,
          this.state.fee,
          coin.contractAddress,
          coin.decimal,
          (hash) => {
            this.setState({
              result: '交易已发送，正在监听交易->' + hash,
            });
          },
        )
          .then(async (res) => {
            console.log('交易已确认', res);
            this.setState({
              success: true,
              modalVisible: false,
            });
            this.sendJoinClubRequest(res.hashId);
          })
          .catch((err) => {
            this.setState({
              success: false,
            });
          });
      },
    );
  };

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
    });
  };

  renderComponent = () => {
    let {modalVisible, loading, success} = this.state;

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Rules"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />

        <ScrollView>
          <View
            style={{
              alignItems: 'center',
            }}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                marginTop: 40,
              }}>
              <Image
                style={{
                  flex: 1,
                  marginHorizontal: 20,
                  fontSize: 0,
                }}
                source={require('../../assets/user/dashed.png')}></Image>
              <Text style={{color: '#fff', fontSize: 18, fontWeight: 'bold'}}>
                Event Description
              </Text>
              <Image
                style={{
                  flex: 1,
                  marginHorizontal: 20,
                }}
                source={require('../../assets/user/dashed.png')}></Image>
            </View>
            <Image
              style={{
                marginTop: 20,
                width: 324,
                height: 584,
              }}
              source={require('../../assets/user/clubrule.png')}></Image>

            {this.state.joinClub ? null : (
              <LinearButton
                text="Open Now"
                buttonStyle={{
                  backgroundColor: '#FFCB26',
                  width: 150,
                  marginTop: 50,
                }}
                onPress={this.opennow}
              />
            )}
          </View>
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>

        <ModalHandler
          visible={modalVisible}
          loading={loading}
          success={success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  gasSymbol: state.Chain.gasSymbol,
  signinClub: state.Chain.signinClub,
  manager: state.Chain.manager,
  coins: state.Chain.coins,
  navigationStack: state.Layout.navigationStack,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(ApplyClubScreen);
